
#include <windows.h>

#include "../inc/KeyBoardMonitor.h"
#include "../inc/Hook.h"


HANDLE slot;






/*
 * Class:     com_yovn_labs_KeyBoardMonitor
 * Method:    enableMonitorN
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_com_yovn_labs_KeyBoardMonitor_enableMonitorN
  (JNIEnv *env, jobject self)
{

    
	int ret= enableHook();
	if(ret==HOOKED)
	{

		/* Create a mailslot for receiving messages */
		slot=CreateMailslot(EVT_CHANNEL_NAME,
		0,
		0,
		(LPSECURITY_ATTRIBUTES) NULL);

		/* Check and see if the mailslot was created */
		if (slot == INVALID_HANDLE_VALUE)
		{
			hookLog( "ERROR: Unable to create a mail slot.\n");
			return (ERR_HOOK);
		}

		
	}
	return ret;


}



/*
 * Class:     com_yovn_labs_KeyBoardMonitor
 * Method:    getNextEvent
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_com_yovn_labs_KeyBoardMonitor_getNextEvent
  (JNIEnv *env, jobject self)
{
	 DWORD NumBytesRead;
	 DWORD nextSize;
	 DWORD msgs;
	 unsigned char evtBuf[4];  
	 BOOL status;

	 status=GetMailslotInfo(slot,
     (LPDWORD) NULL, &nextSize, &msgs,
     (LPDWORD) NULL);

	 if(!status)
	 {
		ErrorExit("Get Status");
	 }
	 if(msgs)
	 {

		  if (!ReadFile(slot, evtBuf,
				sizeof(evtBuf),
				&NumBytesRead, (LPOVERLAPPED) NULL))
		  {
			 ErrorExit("ReadFile");
     
		  }
		  if(NumBytesRead>0)return ((evtBuf[0]<<24)&0xffffffff)|((evtBuf[1]<<16)&0xffffff)|((evtBuf[2]<<8)&0xffff)|(evtBuf[3]&0xff);
	 }

	 


	
    return 0;
	
}



/*
 * Class:     com_yovn_labs_KeyBoardMonitor
 * Method:    disableMonitorN
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_com_yovn_labs_KeyBoardMonitor_disableMonitorN
  (JNIEnv *env, jobject self)
{

	 
	 int ret= disableHook();
	 if(ret==UN_HOOK)
	 {
			CloseHandle(slot);
	 }
	 return ret;
}




